package apiserver

import (
	"bytes"
	"git.hortorgames.com/engine/bon-go"
	"io/ioutil"
	"net/http"
	"sync"
)

type InternalApiClient struct {
	urlRoot  string
	httpPool *sync.Pool
}

func NewInternalApiClient(urlRoot string) *InternalApiClient {
	return &InternalApiClient{
		urlRoot: urlRoot,
		httpPool: &sync.Pool{
			New: func() interface{} {
				return &http.Client{}
			},
		},
	}
}

func (c *InternalApiClient) Call(api string, req interface{}, resp interface{}) *InternalResponse {
	client := c.httpPool.Get().(*http.Client)
	defer c.httpPool.Put(client)
	data := bon.MarshalMust(req)
	buffer := bytes.NewBuffer(data)
	r, err := client.Post(c.urlRoot+api, "application/octet-stream", buffer)
	if err != nil {
		return &InternalResponse{Code: -1, Error: err.Error()}
	}
	if r.StatusCode != 200 {
		return &InternalResponse{Code: -1, Error: r.Status}
	}
	defer r.Body.Close()
	data, err = ioutil.ReadAll(r.Body)
	if err != nil {
		return &InternalResponse{Code: -1, Error: err.Error()}
	}
	respWrap := &InternalResponse{
		Body: resp,
	}
	err = bon.Unmarshal(data, respWrap)
	if err != nil {
		return &InternalResponse{Code: -1, Error: err.Error()}
	}
	return respWrap
}
